package logv

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/rs/zerolog"
)

// HTTPMiddleware HTTP中间件示例
func HTTPMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 为每个请求创建新的context和追踪ID
		ctx := WithNewTraceID(r.Context())
		ctx = WithNewRequestID(ctx)

		// 记录请求开始
		InfoCtx(ctx, "HTTP请求开始")
		WithFieldsCtx(ctx, map[string]interface{}{
			"method":     r.Method,
			"path":       r.URL.Path,
			"user_agent": r.UserAgent(),
			"remote_ip":  r.RemoteAddr,
		}).Msg("请求详情")

		start := time.Now()

		// 将context传递给下一个处理器
		r = r.WithContext(ctx)
		next(w, r)

		// 记录请求完成
		duration := time.Since(start)
		WithFieldsCtx(ctx, map[string]interface{}{
			"duration_ms": duration.Milliseconds(),
			"status":      "completed",
		}).Msg("HTTP请求完成")
	}
}

// UserHandler 用户处理器示例
func UserHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	InfoCtx(ctx, "开始处理用户请求")

	// 模拟业务逻辑
	userID := r.URL.Query().Get("id")
	if userID == "" {
		ErrorCtx(ctx, "缺少用户ID参数")
		http.Error(w, "Missing user ID", http.StatusBadRequest)
		return
	}

	// 模拟数据库查询
	user, err := getUserFromDB(ctx, userID)
	if err != nil {
		WithErrorCtx(ctx, err).Msg("获取用户信息失败")
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	WithFieldsCtx(ctx, map[string]interface{}{
		"user_id":   user.ID,
		"user_name": user.Name,
	}).Msg("成功获取用户信息")

	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"id": "%s", "name": "%s"}`, user.ID, user.Name)

	InfoCtx(ctx, "用户请求处理完成")
}

// User 用户结构体
type User struct {
	ID   string
	Name string
}

// getUserFromDB 模拟从数据库获取用户
func getUserFromDB(ctx context.Context, userID string) (*User, error) {
	DebugCtx(ctx, "开始数据库查询")

	WithFieldsCtx(ctx, map[string]interface{}{
		"table":   "users",
		"user_id": userID,
	}).Msg("执行数据库查询")

	// 模拟查询延迟
	time.Sleep(10 * time.Millisecond)

	if userID == "404" {
		return nil, fmt.Errorf("用户不存在: %s", userID)
	}

	user := &User{
		ID:   userID,
		Name: "用户" + userID,
	}

	DebugCtx(ctx, "数据库查询完成")
	return user, nil
}

// 演示HTTP服务器
func demonstrateHTTPServer() {
	SetLevel(zerolog.DebugLevel)

	Info("启动HTTP服务器演示")

	// 注册路由
	http.HandleFunc("/user", HTTPMiddleware(UserHandler))

	Info("HTTP服务器已启动，访问 http://localhost:8080/user?id=123")

	// 模拟一些请求（实际使用中这些请求来自客户端）
	simulateRequests()
}

// 模拟请求
func simulateRequests() {
	// 这里只是演示日志输出，实际的HTTP服务器需要真实启动
	Info("模拟HTTP请求...")

	// 模拟正常请求
	ctx1 := WithNewTraceID(context.Background())
	ctx1 = WithNewRequestID(ctx1)
	InfoCtx(ctx1, "模拟请求: GET /user?id=123")
	WithFieldsCtx(ctx1, map[string]interface{}{
		"method":   "GET",
		"path":     "/user",
		"query":    "id=123",
		"status":   200,
		"duration": "15ms",
	}).Msg("请求处理完成")

	// 模拟错误请求
	ctx2 := WithNewTraceID(context.Background())
	ctx2 = WithNewRequestID(ctx2)
	InfoCtx(ctx2, "模拟请求: GET /user?id=404")
	WithFieldsCtx(ctx2, map[string]interface{}{
		"method":   "GET",
		"path":     "/user",
		"query":    "id=404",
		"status":   404,
		"error":    "用户不存在",
		"duration": "8ms",
	}).Msg("请求处理完成")
}

func main() {
	demonstrateHTTPServer()
	Close()
}
